package com.rjkj.medicalwaste.ui.storage

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.rjkj.medicalwaste.MainActivity
import com.rjkj.medicalwaste.base.initTip
import com.rjkj.medicalwaste.base.showTip
import com.rjkj.medicalwaste.databinding.DialogFixedCodeBinding
import com.rjkj.medicalwaste.livedatabus.LiveDataBus
import com.rjkj.medicalwaste.utils.StringUtils
import com.rjkj.medicalwaste.viewmodels.BoxListViewModel
import com.rjkj.medicalwaste.viewmodels.UnBoxedViewModel
import com.rjkj.medicalwaste.viewmodels.UserViewModel
import com.rjkj.medicalwaste.viewmodels.provider.MainViewModelProvider
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


class ScanFixedBoxDialog : DialogFragment() {
    var callBack:Callback? = null
    private val unBoxedViewModel:UnBoxedViewModel by viewModels {
        MainViewModelProvider.provideUnBoxedModel(requireContext())
    }
    private val boxListViewModel: BoxListViewModel by activityViewModels()
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val binding = DialogFixedCodeBinding.inflate(inflater, container, false)
        binding.lifecycleOwner = viewLifecycleOwner
        onSubscribeUi(binding)
        return binding.root
    }

    fun onSubscribeUi(binding: DialogFixedCodeBinding) {
        binding.imClose.setOnClickListener {
            dismiss()
        }
        boxListViewModel.scanFixBoxCode.observe(viewLifecycleOwner){
            if (StringUtils.checkBoxQrCode(it)){
                lifecycleScope.launch{
                    val findBoxByBoxCode = unBoxedViewModel.repository.findBoxByBoxCode(it)
                    if(findBoxByBoxCode.isNullOrEmpty()){
                        dismiss()
                        callBack?.onGetCode(it)
                    }else{
                        showTip("箱码已存在")
                    }

                }

            }else{
                showTip("请勿扫描其他二维码")
            }
        }


    }

    interface Callback {
        fun onGetCode(code:String)
    }

    override fun onStart() {
        dialog!!.window!!.apply {
            attributes.gravity = Gravity.CENTER//位于底部
            decorView.background = ColorDrawable(Color.TRANSPARENT)//背景色
        }
        super.onStart()
    }


}